<template>
  <div class="cart">
    <h2>我的购物车</h2>
    <NList style="min-height: 19vh" bordered>
      <NListItem v-for="(v, k) of user.currentOrderItems" :key="k">
        <div class="cart-item">
          <img class="image" :src="v.ImgUrl" alt="" srcset="" />
          <h3 class="name">{{ v.Name }}</h3>
          <NInputNumber
            class="number"
            :value="v.Number"
            @update:value="(number) => handleNumber({ id: v.ID, number })"
            :min="1"
          />
          <NButton @click="remove(v.ID)" type="error">删除</NButton>
        </div>
      </NListItem>
    </NList>
    <div class="pay">
      <span class="money">￥{{ user.totalPrice }}</span>
      <NButton @click="pay" size="large" type="error">结算</NButton>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { NList, NListItem, NInputNumber, NButton, useMessage } from "naive-ui";
import { useUserStore } from "@/stores/user";
import { useOrderItem } from "@/hooks/OrderItem";

const message = useMessage();
const user = useUserStore();
const { editOrderItem, removeOrderItemByID } = useOrderItem();

async function remove(id: number) {
  const msg = await removeOrderItemByID(id);
  await user.getCurrentOrderItems();
  message.success(msg);
}

async function handleNumber(params: any) {
  await editOrderItem(params);
  await user.getCurrentOrderItems();
}

async function pay() {
  try {
    const msg = await user.payCurrentOrder();
    message.success(msg);
  } catch (e: any) {
    message.error(e.response.data.msg);
  }
}
</script>

<style lang="less" setup>
.cart {
  margin: 0 1em;
  padding: 2em;
  background-color: white;
  border: 1px solid var(--border-color);

  > * + * {
    margin-top: 1em;
  }

  .cart-item {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .name {
      width: 20%;
      min-width: 3em;
    }

    .image {
      max-width: 6em;
    }

    .number {
      max-width: 9em;
    }
  }

  .pay {
    padding: 1em;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 3em;

    .money {
      font-size: 1.75em;
      color: red;
    }
  }
}
</style>
